package com.example.fragmenttest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.bt_left);
        button.setOnClickListener(this);
        replaceFragment(new RightFragment()); //动态添加了RightFragment碎片 1


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_left:
                //将 1换成了 AnotherRightFragment 碎片
                replaceFragment(new AnotherRightFragment());
                break;
            default:
                break;
        }
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager(); //2 获取fragmentManager
        FragmentTransaction transaction = fragmentManager.beginTransaction(); //3开启一个事务 通过beginTransaction开启
        transaction.replace(R.id.right_laypout, fragment);//4.向容器添加或替换碎片
        transaction.addToBackStack(null); //返回栈  返回上一个碎片

        transaction.commit();//5.提交事务 调用commit()方法来完成
    }
}

